package cn.tedu.storedemo.interceptor;

import cn.tedu.storedemo.entity.UserEntity;
import cn.tedu.storedemo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 * 需要登录才能放行
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    IUserService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断用户是否已登录
        HttpSession session=request.getSession();
        UserEntity user=(UserEntity) session.getAttribute("user");
        if(user!=null){ // 已登录
            return true; // 放行
        }
        // 判断是否携带了autoLogin的Cookie
        Cookie autoLogin=null;
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie c:cookies){
                if(c.getName().equals("autoLogin")){
                    autoLogin=c;
                    break;
                }
            }
        }
        if(autoLogin!=null){ // 携带了自动登录cookie
            // 验证用户名和密码是否正确
            String username=autoLogin.getValue().split("_#_")[0];
            System.err.println("username="+username);
            String password=autoLogin.getValue().split("_#_")[1];
            try{
                System.err.println("ssss");
                UserEntity userEntity=service.autoLogin(username,password);
                session.setAttribute("user",userEntity);
                return true; // 放行
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        String path=request.getServletContext().getContextPath();
        // 重定向到登录页面
        response.sendRedirect(path+"/web/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
